// The LoginManager. Used to store login session data
window.AccountManager = {
	register: function(mail, password, firstName, lastName, groupUri, callback) {
		var data = { "email": mail, "key": hex_md5(mail + password), "firstName": firstName, "lastName": lastName, "groupUri": groupUri };
		$('.alert-error').hide();
		
        $.ajax({
            url: '/api/auth',
            type:'PUT',
            accepts : "application/json",
    		contentType : "application/json",
    		processData : false,
    		dataType : "text",
            data: JSON.stringify(data),
            success: function (data) {
            	if(callback) callback();
            },
            error: function(data) {
            	var msg = "Server error " + data.status + ". Please try again later.";
            	if(data.status == 409) 
            		msg = "E-mail already exists.";
            	else if(data.status == 400)
            		msg = "Invalid input data.";
            	
            	 $('.alert-error').text(msg).show();
            }
        });
	},
		
	login: function(mail, password, callback) {
		var data = { key: hex_md5(mail + password) };
		$('.alert-error').hide();
		
        $.ajax({
            url: '/api/auth',
            type:'POST',
            accepts : "application/json",
    		contentType : "application/json",
    		processData : false,
    		dataType : "text",
            data: JSON.stringify(data),
            success: function (data) {
            	if(callback) callback();
            },
            error: function(data) {
            	var msg = "Server error " + data.status + ". Please try again later.";
            	if(data.status == 404) 
            		msg = "Account not found.";
            	else if(data.status == 400)
            		msg = "Invalid input data.";
            	
            	 $('.alert-error').text(msg).show();
            }
        });
	},
	
	logout: function(callback) {
        $.ajax({
            url: '/api/auth',
            type:'POST',
            accepts : "application/json",
    		contentType : "application/json",
    		processData : false,
    		dataType : "text",
            data: '{}',
            complete: function (data) {    
            	sessionStorage.clear();
        		$.removeCookie("k");
        		$.removeCookie("p");
            	if(callback) callback();
            }
        });
	},
	
	getKey: function() {
		return $.cookie("k");
	}
};